package Server;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author PZK
 *
 */
public class Sender extends Thread {

	private PrintWriter out;
	List<String> messages;

	public Sender(Socket socket) {

		messages = Collections.synchronizedList(new ArrayList<String>());

		try {
			out = new PrintWriter(new OutputStreamWriter(
					socket.getOutputStream()));
		} catch (IOException e) {
			e.printStackTrace();
		}

		start();

	}

	public synchronized void send(String message) {

		messages.add(message);
		notify();

	}

	private void sendToClient(String message) {

		out.println(message);
		out.flush();

	}

	private synchronized String nextMessage() throws InterruptedException {
		while (messages.size() == 0)
			wait();
		String message = messages.get(0);
		messages.remove(0);

		return message;
	}

	@Override
	public void run() {

		try {
			while (!isInterrupted()) {
				String message = nextMessage();
				sendToClient(message);
				System.out.println("SENT: "+message);
			}
		} catch (Exception e) {
			// connection interrupted
		}

		//clientHandler.removeClient(client);

	}

}
